package hcd.mynote;

import android.util.Log;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

public class Bmob {
    public static String bmobUrl = "http://api.bmob.cn/1/classes/note";
    public static String userUrl = "http://api.bmob.cn/1/classes/user";

    public static int login(String username, String password) throws Exception {
        JSONObject user = userQuery(username);
        if (user == null) return 1;
        if (!user.getString("password").equals(password)){
            return 2;
        }
        return 0;

    }

    public static boolean register(String username, String password){
        try{
            if(userQuery(username) != null) return false;
            String result = sendPostRequest(userUrl, "{" +
                    "\"username\":\""+username+"\"," +
                    "\"password\":\""+password+"\"" +
                    "}");
            JSONObject resultObj = new JSONObject(result);
            if (!resultObj.has("objectId")) throw new Exception("insert failed.");
            return true;
        }catch (Exception e){
            return false;
        }
    }

    public static JSONObject userQuery(String username) throws Exception {
        String json = sendGetRequest(userUrl + "?where={\"username\":\""+username+"\"}");
        Log.d("userQuery: ", json);
        JSONObject jsonObject = new JSONObject(json);
        JSONArray data = jsonObject.getJSONArray("results");
        if (data.length() == 0) return null;
        return data.getJSONObject(0);
    }

    public static ArrayList<Note> getNotes(String username) throws Exception{
        String json = sendGetRequest(bmobUrl + "?where={\"username\":\""+username+"\"}&keys=createTimestamp,title,content,modifyTimestamp");
        Log.d("getNotes: ", json);
//        String json = sendPostRequest(bmobUrl, "keys=createTimestamp,title,content,modifyTimestamp");
        JSONObject jsonObject = new JSONObject(json);
        JSONArray data = jsonObject.getJSONArray("results");
        ArrayList<Note> result = new ArrayList<>();
        for (int i=0; i < data.length(); i++){
            JSONObject item = data.getJSONObject(i);
            result.add(new Note(
                    item.getString("title"),
                    item.getString("content"),
                    Long.parseLong(item.getString("modifyTimestamp")),
                    Long.parseLong(item.getString("createTimestamp"))
            ));
        }
        return result;
    }

    public static void saveNote(Note note, String username) throws Exception {
        // 查询是否存在
        String exist = sendGetRequest(bmobUrl + "?where={\"createTimestamp\":\""+note.getCreateTime()+"\",\"username\":\""+username+"\"}&keys=objectId");
        JSONObject jsonObject = new JSONObject(exist);
        JSONArray data = jsonObject.getJSONArray("results");
        if (data.length() > 0){
            // 存在，更新
            String objId = data.getJSONObject(0).getString("objectId");
            String result = sendRequest(bmobUrl+"/"+objId, "{" +
                    "\"title\":\""+note.getTitle()+"\"," +
                    "\"content\":\""+note.getContent()+"\"," +
                    "\"modifyTimestamp\":\""+note.getTime()+"\"" +
                    "}", "PUT");
            JSONObject resultObj = new JSONObject(result);
            if (!resultObj.has("updatedAt")) throw new Exception("update failed.");

        }else {
            // 不存在，添加
            String result = sendPostRequest(bmobUrl, "{" +
                    "\"username\":\""+username+"\"," +
                    "\"createTimestamp\":\""+note.getCreateTime()+"\"," +
                    "\"title\":\""+note.getTitle()+"\"," +
                    "\"content\":\""+note.getContent()+"\"," +
                    "\"modifyTimestamp\":\""+note.getTime()+"\"" +
                    "}");
            JSONObject resultObj = new JSONObject(result);
            if (!resultObj.has("objectId")) throw new Exception("insert failed.");
        }

    }

    public static void deleteNote(String createTime, String username) throws Exception {
        // 查询是否存在
        String exist = sendGetRequest(bmobUrl + "?where={\"createTimestamp\":\""+createTime+"\",\"username\":\""+username+"\"}&keys=objectId");
        JSONObject jsonObject = new JSONObject(exist);
        JSONArray data = jsonObject.getJSONArray("results");
        if (data.length() > 0){
            // 存在，更新
            String objId = data.getJSONObject(0).getString("objectId");
            String result = sendRequest(bmobUrl+"/"+objId, null, "DELETE");
            JSONObject resultObj = new JSONObject(result);
            if (!resultObj.getString("msg").equals("ok")) throw new Exception("delete failed");

        }else {
            throw new Exception("not exist");
        }
    }

    public static String sendGetRequest(String url) throws Exception {
        return  sendRequest(url, null, "GET", false);
    }

    public static String sendPostRequest(String url, String data) throws Exception {
        return sendRequest(url, data, "POST", true);
    }

    public static String sendRequest(String url, String data, String method) throws Exception {
        return sendRequest(url, data, method, true);
    }

    public static String sendRequest(String url, String data, String method, boolean json) throws Exception{
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setRequestMethod(method);
//        connection.setRequestProperty("Content-Type", json ? "application/json" : "");
        if (json) connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("X-Bmob-Application-Id", "cd941780fe6377462de44459a109d5e8");
        connection.setRequestProperty("X-Bmob-REST-API-Key", "2f0d4a50e7f223ce6b8b9666bcf335cd");
        connection.setDoInput(true);
        connection.setDoOutput(!method.equals("GET"));
        if (data != null){
            PrintWriter writer = new PrintWriter(connection.getOutputStream());
            writer.write(data);
            writer.flush();
            writer.close();
        }

        connection.connect();

        StringBuilder result = new StringBuilder();
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            result.append(line);
        }
        reader.close();

        connection.disconnect();

        return result.toString();
    }

}